import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:pp_uikit/theme/pp_default_theme.dart';
import 'package:pp_uikit/theme/pp_group_theme.dart';

// ignore: must_be_immutable
class PPTextField extends StatefulWidget {
  /// 输入框的初始值，默认为""
  final String contentText;

  /// 录入项 是否可编辑
  final bool enabled;

  /// 提示文案
  final String? hint;

  /// 输入内容类型
  final TextInputType inputType;

  /// 是否自动获取焦点
  bool autofocus;

  /// 输入字符数上限
  final int? maxLength;

  final TextAlign textAlign;

  /// 指定对输入数据的格式化要求
  final List<TextInputFormatter>? inputFormatters;

  /// 输入变化回调
  final ValueChanged<String>? onChanged;

  /// 点击确定后的回调
  final ValueChanged<String>? onSubmitted;

  /// 用于对 TextField  更精细的控制，若传入该字段，[contentText] 参数将失效，可使用 TextEditingController.text 进行赋值。
  final TextEditingController? controller;

  final FocusNode? focusNode;

  /// 背景色
  final Color? backgroundColor;

  /// 是否密码
  final bool obscureText;

  double? borderRadius;

  EdgeInsets contentPadding;

  /// form配置
  PPGroupTheme? themeData;

  PPTextField({
    Key? key,
    this.contentText = "",
    this.enabled = true,
    this.hint,
    this.maxLength,
    this.autofocus = false,
    this.obscureText = false,
    this.inputType = TextInputType.text,
    this.textAlign = TextAlign.left,
    this.inputFormatters,
    this.onChanged,
    this.onSubmitted,
    this.controller,
    this.focusNode,
    this.borderRadius,
    this.backgroundColor,
    this.contentPadding = const EdgeInsets.fromLTRB(12, 8, 12, 8),
    double fontSize = 16.0,
    this.themeData,
  }) : super(key: key) {
    themeData ??= PPGroupTheme(
      contentTextStyle: TextStyle(
        fontSize: fontSize,
        color: PPDefaultTheme.instance.colorTextBase,
      ),
      disableTextStyle: TextStyle(
        fontSize: fontSize,
        color: const Color(0xFF999999),
      ),
      hintTextStyle: TextStyle(
        fontSize: fontSize,
        color: const Color(0xFF999999),
      ),
    );
  }

  @override
  State<StatefulWidget> createState() {
    return PPTextFieldState();
  }
}

class PPTextFieldState extends State<PPTextField> {
  late TextEditingController _controller;
  late FocusNode _focusNode;

  @override
  void initState() {
    String textData = widget.contentText;
    if (widget.maxLength != null &&
        widget.contentText.runes.length > widget.maxLength!) {
      var sRunes = textData.runes;
      textData = String.fromCharCodes(sRunes, 0, widget.maxLength);
    }
    var tmpController = widget.controller;
    if (tmpController == null) {
      if (textData.isNotEmpty) {
        tmpController = TextEditingController.fromValue(
          TextEditingValue(
            text: textData,
            selection: TextSelection.fromPosition(
              TextPosition(
                affinity: TextAffinity.downstream,
                offset: textData.length,
              ),
            ),
          ),
        );
      } else {
        tmpController = TextEditingController();
      }
    }
    _controller = tmpController;
    var tmpFocusNode = widget.focusNode;
    if (tmpFocusNode == null) {
      _focusNode = FocusNode();
    } else {
      _focusNode = tmpFocusNode;
    }

    // 监听焦点变化，并在焦点变为focused时将光标移动到最右边。
    _focusNode.addListener(() {
      if (_focusNode.hasFocus) {
        _controller.selection =
            TextSelection.collapsed(offset: _controller.text.length);
      }
    });
    super.initState();
  }

  /// 获取是否可编辑的字体
  TextStyle? _getEditTextStyle(bool isEdit) {
    PPGroupTheme? themeData = widget.themeData;
    return isEdit ? themeData?.contentTextStyle : themeData?.disableTextStyle;
  }

  @override
  Widget build(BuildContext context) {
    return TextField(
      autofocus: widget.autofocus,
      keyboardType: widget.inputType,
      enabled: widget.enabled,
      maxLines: 1,
      maxLength: widget.maxLength,
      // 是否密码
      obscureText: widget.obscureText,
      // 样式属性，用于正在编辑的文本的样式。
      style: _getEditTextStyle(widget.enabled),
      // 光标颜色属性，绘制光标时使用的颜色。
      cursorColor: PPDefaultTheme.instance.brandPrimary,
      // 光标宽度属性，光标的厚度，默认是2.0。
      cursorWidth: 2.0,
      decoration: InputDecoration(
        // border: InputBorder.none,
        // 提示样式属性，用于提示文本（`hintText`）的样式。
        hintStyle: widget.themeData?.hintTextStyle,
        hintText: widget.hint,
        counterText: "",
        contentPadding: widget.contentPadding,
        isDense: true,
        // 无光标时的边框
        enabledBorder: widget.borderRadius != null
            ? OutlineInputBorder(
                borderRadius: BorderRadius.circular(widget.borderRadius ?? 0),
                borderSide: const BorderSide(color: PPDefaultTheme.borderColor),
              )
            : const OutlineInputBorder(
                borderSide: BorderSide(color: Colors.transparent)),
        // 有光标时的边框
        focusedBorder: widget.borderRadius != null
            ? OutlineInputBorder(
                borderRadius: BorderRadius.circular(widget.borderRadius ?? 0),
                borderSide: const BorderSide(color: PPDefaultTheme.borderColor),
              )
            : const OutlineInputBorder(
                borderSide: BorderSide(color: Colors.transparent)),
      ),
      textAlign: widget.textAlign,
      controller: _controller,
      focusNode: _focusNode,
      inputFormatters: widget.inputFormatters,
      onChanged: widget.onChanged,
      onSubmitted: widget.onSubmitted,
    );
  }

  @override
  void dispose() {
    super.dispose();

    // 如果controller由外部创建不需要销毁, 若由内部创建则需要销毁
    if (widget.controller == null) {
      _controller.dispose();
    }
    if (widget.focusNode == null) {
      _focusNode.dispose();
    }
  }
}
